<template>
  <tl-sub-page :render="render" ref="drawerRef" :visible.sync="visible" :with-header="false" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true" class="tl-drawer" :size="'95%'" @open="open" @close="close" :destroy-on-close="true">
    <div class="mpm-project-container">
      <div style="width:0px;overflow:hidden;height:0px;"><input type="text" /></div>
      <div class="mpm-project-header">
        <div class="info">
          <img src="/static/images/paojectManager/mpm_project.png" class="logo" style="width: 55px;height: 55px" />
          <div class="content" :title="model.projectname">
            <p>
              <b v-if="model.id && model.projectname">{{ model.projectname + '-' }}</b>
              <b>项目立项</b>
            </p>
            <p class="light">
              <span v-if="model.projectcode">项目编号：{{ model.projectcode }}</span>
              <span>项目经理：{{ model.projectmanager ? model.projectmanager + '【' + model.projectmanagercode + '】' : user.name + '【' + user.code + '】' }}</span>
              <span v-if="model.createon">创建时间：{{ formatDate(model.createon) }}</span>
            </p>
          </div>
        </div>
        <div class="toolbar">
          <el-button type="danger" size="small" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div>
      </div>
      <div class="mpm-project-nav" :style="{ height: mainHeight + 'px', top: '60px' }">
        <ul class="nav-list">
          <template v-for="item in navList">
            <li :key="item.code" :class="item.on ? 'on' : ''" @click="clickNav(item.code)" style="cursor: pointer;clear: both">
              <span style="float: left;width: 150px">{{ item.name }}</span>
              <span style="float: left;">
                <i v-if="item.count > 0">{{ item.count }}</i>
                <label v-if="item.flag">{{ item.flag }}</label>
              </span>
            </li>
          </template>
        </ul>
      </div>
      <div class="mpm-project-main" :style="{ height: mainHeight + 'px' }">
        <el-scrollbar class="mpm-project-main-container" id="mpmMainContainer">
          <div style="padding:0 10px">
            <!-- PMO标准化节点显示 -->
            <el-form v-if="extraParam === 'PMO'" class="tl-form" style="margin-top: 20px" ref="PMONodeForm" :model="model" :rules="rules" label-width="120px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目类型" prop="pmoprojecttype" :rules="rules.validateRequire">
                    <el-select v-model="model.pmoprojecttype" filterable>
                      <el-option v-for="item in codeModel.pmoprojecttypeList" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <!-- CEO审批显示 -->
            <el-form v-if="extraParam === 'CEO'" class="tl-form" style="margin-top: 20px" ref="ceodealform" :model="model" :rules="rules" label-width="120px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="审批类型" prop="approvaltype" :rules="rules.validateRequire">
                    <el-select
                      v-model="model.approvaltype"
                      filterable
                      clearable
                      @change="
                        (val) => {
                          openMeetDialog(val, 'meetEdit')
                        }
                      "
                    >
                      <el-option v-for="item in codeModel.mpmApprovalTypeList" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <div v-if="model.approvaltype === '1'">
                <a id="ceomeetresolution" class="step-position">&nbsp;</a>
                <div class="tl-form-line-title">
                  会议决议记录
                </div>
                <meet-list-comp ref="meetlist" :disableEditSubmit="disableEditSubmit" :sourcetype="'meetResolution'" :projectid="model.id" :attendcodes="model.decisionusercode" :attendnames="model.decisionusername"></meet-list-comp>
              </div>
            </el-form>
            <!-- 林总邀请审批和林总审批显示 -->
            <el-form v-if="extraParam === 'LIN' || extraParam === 'LINInvite'" class="tl-form" ref="lindealform" :model="model" :rules="rules" label-width="120px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目级别" prop="projectlevel" :rules="rules.validateRequire">
                    <el-select v-model="model.projectlevel" filterable clearable>
                      <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code" :disabled="item.code === '3'" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <!-- 林总邀请审批显示 -->
            <el-form v-if="extraParam === 'LINInvite'" class="tl-form" ref="lininvitedealform" :model="model" :rules="rules" label-width="120px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="邀请决策" prop="invitedecisionusername">
                    <el-input v-model="model.invitedecisionusername" class="tl-ref-selector" disabled>
                      <el-button slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectResourcePoolDialog"></el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-row v-if="extraParam === 'CEO' || extraParam === 'LIN' || extraParam === 'LINInvite'">
              <el-col :span="24">
                <el-divider content-position="center"><span>【以下信息为只读信息】</span></el-divider>
              </el-col>
            </el-row>
            <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
              <a id="basic" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                立项信息
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目来源" prop="projectsource">
                    <el-select v-model="model.projectsource" @change="changeSource" filterable clearable>
                      <el-option v-for="item in codeModel.projectSourceList" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item :label="leadOrChanceLabel" prop="chanceclue">
                    <el-input v-model="model.chanceclue" disabled class="tl-ref-selector">
                      <el-button slot="append" type="primary" icon="el-icon-search" @click="openChanceclueDialog" v-if="!disableSave"></el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="1">
                  <el-popover trigger="hover" placement="left">
                    此处可关联的线索、机会点为本人负责，并且线索需要处于“跟踪和培育”阶段，机会点处于“标前引导”阶段且是否立项应为“是”
                    <i slot="reference" class="el-icon-info" style="font-size: 20px;margin-left: 4px;margin-top: 3px;color: #909399" />
                  </el-popover>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="projectname" :rules="rules.rulesForInfo">
                    <el-input v-model="model.projectname"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="项目级别" prop="projectlevel" :rules="rules.rulesForInfo">
                    <el-row type="flex">
                      <el-select v-model="model.projectlevel" filterable clearable class="levelSelect" :disabled="model.state === 1">
                        <el-option v-for="item in projectlevelList" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                      <el-button type="primary" icon="el-icon-edit-outline" class="levelButton" @click="openChangeLevelDialog" v-if="model.state === 1"></el-button>
                    </el-row>
                  </el-form-item>
                </el-col>
                <el-col :span="1">
                  <el-popover trigger="hover" placement="left">
                    <el-table :data="gridData" :span-method="objectSpanMethod" :border="true">
                      <el-table-column width="120" property="projectlevel" label="项目级别" align="center"></el-table-column>
                      <el-table-column min-width="400" property="projectleveldetail" label="项目级别定义" header-align="center"></el-table-column>
                      <el-table-column width="100" property="sponsor" label="Sponsor" header-align="center"></el-table-column>
                      <el-table-column width="120" property="owner" label="Owner" header-align="center"></el-table-column>
                      <el-table-column width="120" property="manager" label="PM" header-align="center"></el-table-column>
                    </el-table>
                    <div style="font-size: 15px">注：以上是项目级别的实施原则，如果与上述原则产生异议，可以在立项决策会上申请调级。</div>
                    <i slot="reference" class="el-icon-question" style="font-size: 20px;margin-left: 4px;margin-top: 3px;color: #909399" />
                  </el-popover>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="客户名称" prop="clientname" :rules="rules.rulesForInfo">
                    <el-input v-model="model.clientname" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户部门" prop="clientdept" :rules="rules.rulesForInfo">
                    <el-input v-model="model.clientdept" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <!-- <el-form-item label="可参与金额" prop="participatemoney" :rules="model.projectsource === '1' ? [] : rules.rulesForInfo"> <el-input-number v-model="model.participatemoney" :disabled="midChangePoint && model.projectsource !== '1'" controls-position="right" :step="1" :min="0" :precision="2" class="unitInputNumber"></el-input-number><span class="unitSpan">万元</span> </el-form-item> -->
                  <el-form-item label="可参与金额" prop="participatemoney"> <el-input-number v-model="model.participatemoney" disabled controls-position="right" :step="1" :min="0" :precision="2" class="unitInputNumber"></el-input-number><span class="unitSpan">万元</span> </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="采购模式" prop="purchasepattern" :rules="rules.rulesForInfo">
                    <el-select v-model="model.purchasepattern" filterable clearable>
                      <el-option v-for="item in codeModel.MpmPurchasePatternList" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="计划开始日期" prop="planstartdate" :rules="rules.rulesForInfo">
                    <el-date-picker v-model="model.planstartdate" type="date" placeholder="例：2022-01-01" value-format="yyyy-MM-dd" @change="planStart"> </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计划结束日期" prop="planenddate" :rules="rules.rulesForInfo">
                    <el-date-picker v-model="model.planenddate" type="date" placeholder="例：2021-02-01" value-format="yyyy-MM-dd" @change="planEnd"> </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="需求上报时间" prop="demandbegindate" :rules="model.purchasepattern === '11' || model.purchasepattern === '13' ? rules.validateRequire : []">
                    <el-date-picker v-model="model.demandbegindate" type="date" placeholder="例：2022-01-01" value-format="yyyy-MM-dd"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="需求截止时间" prop="demandenddate" :rules="model.purchasepattern === '11' || model.purchasepattern === '13' ? rules.validateRequire : []">
                    <el-date-picker v-model="model.demandenddate" type="date" placeholder="例：2022-01-01" value-format="yyyy-MM-dd"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="创建部门" prop="deptname" :rules="rules.rulesForInfo">
                    <el-input v-model="model.deptname" :disabled="true"></el-input>
                    <!-- <tl-ref-dept v-model="model.deptname" :initDisplayData.sync="model.deptname" dataType="code" nameType="fullname" @confirm="onSelectDept" :singleSelect="true" :externalQueryParam="{ qry_enabled: 1 }" :disabled="disableEditSubmit || disableSave"> </tl-ref-dept> -->
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="区域" prop="deptname1" :rules="rules.validateRequire">
                    <el-cascader style="width:100%" :options="provinceCityList" :props="{ checkStrictly: true }" v-model="deptname" filterable @change="changeDeptname" clearable> </el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="Sponsor" prop="sponsorcode" :rules="model.projectlevel === '0' || model.projectlevel === '1' ? rules.rulesForInfo : []">
                    <tl-ref-user v-model="model.sponsorcode" :initDisplayData.sync="model.sponsor" dataType="code" :singleSelect="true" :disabled="disableEditSubmit || disableSave"> </tl-ref-user>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="Owner" prop="ownercode" :rules="rules.rulesForInfo">
                    <tl-ref-user v-model="model.ownercode" :initDisplayData.sync="model.owner" dataType="code" :singleSelect="true" :disabled="disableEditSubmit || disableSave"> </tl-ref-user>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="决策组人员" prop="decisionusername" :rules="rules.rulesForInfo">
                    <el-input v-model="model.decisionusername" class="tl-ref-selector" disabled>
                      <el-button slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectResourcePoolDialog" v-if="!disableSave"></el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目经理" prop="projectmanagercode" :rules="rules.rulesForInfo">
                    <tl-ref-user v-model="model.projectmanagercode" :initDisplayData.sync="model.projectmanager" dataType="code" :singleSelect="true" :disabled="disableEditSubmit || disableSave"> </tl-ref-user>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="historyLevel && model.projectlevel !== historyLevel">
                <el-col :span="12">
                  <el-form-item label="原项目级别">
                    <el-input v-model="historyLevel" class="tl-ref-selector" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="model.changelevelreason">
                <el-col :span="24">
                  <el-form-item label="项目级别调整原因" prop="changelevelreason" :rules="rules.rulesForInfo">
                    <el-input v-model="model.changelevelreason" type="textarea" :rows="4" maxlength="1000" show-word-limit> </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="招标批次" prop="bidinfo" :rules="bidDateTime ? rules.validateRequire : []">
                    <el-input v-model="model.bidinfo" placeholder="请填写批次全称，如国网**省电力公司**年第**次**招标"> </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="挂网日期" prop="bidbegindate" :rules="bidDateTime ? rules.validateRequire : []">
                    <el-date-picker v-model="model.bidbegindate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="bidbegindate"> </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="开标日期" prop="bidenddate" :rules="bidDateTime ? rules.validateRequire : []">
                    <el-date-picker v-model="model.bidenddate" :class="{ 'red-border': ifRedBorder }" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="bidenddate"> </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="model.projectlevel === '0' || model.projectlevel === '1'">
                <el-col :span="12">
                  <el-form-item label="春季/秋季攻势" prop="projectattack">
                    <el-select v-model="model.projectattack" filterable clearable>
                      <el-option v-for="item in projectattackList" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <tl-project-bid-date ref="projectBidDate" :projectid="model.id" :planstartdate="model.planstartdate" :planenddate="model.planenddate" :biddatetime="bidDateTime"></tl-project-bid-date> -->
              <div v-if="model.approvaltype === '1' && extraParam !== 'CEO'">
                <a id="meetresolution" class="step-position">&nbsp;</a>
                <div class="tl-form-line-title">
                  会议决议记录
                </div>
                <meet-list-comp ref="meetlist" :disableEditSubmit="disableEditSubmit || extraParam !== 'CEO'" :sourcetype="'meetResolution'" :projectid="model.id"></meet-list-comp>
              </div>
              <a id="product" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                涉及产品范围
              </div>
              <el-row v-if="model.productlist && model.productlist.length > 0 && Array.isArray(model.productlist)">
                <el-col>
                  <el-divider content-position="center"><span style="font-size:16px">【内部产品】</span></el-divider>
                </el-col>
                <el-row v-for="(item, index) in model.productlist" :key="index">
                  <el-col :span="8">
                    <el-button type="text" @click="deleteProductRange(index)" size="medium" v-show="!(disableEditSubmit || disableSave)" style="float: left;padding-top: 6px"><i class="el-icon-remove-outline"></i>删除</el-button>
                    <el-form-item label="产品线/事业部" label-width="100px" style="margin-left: 50px">
                      <el-select v-model="item.productlinecode" :disabled="true">
                        <el-option v-for="item in codeModel.productlineList" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="产品类别">
                      <el-select v-model="item.productcode" :disabled="true" v-if="model.projectsource === '1'">
                        <el-option v-for="item in codeModel.productcatalog1List" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                      <el-select v-model="item.productcode" :disabled="true" v-if="model.projectsource === '2'">
                        <el-option v-for="item in codeModel.productcatalog2List" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="金额" :prop="'productlist.' + index + '.fund'" :rules="rules.rulesForFundInfo"> <el-input-number v-model="item.fund" disabled controls-position="right" :step="1" :min="0" :precision="2" class="unitInputNumber"></el-input-number><span class="unitSpan">万元</span> </el-form-item>
                  </el-col>
                </el-row>
              </el-row>
              <el-row v-if="model.productoutlist && model.productoutlist.length > 0 && Array.isArray(model.productoutlist)">
                <el-col>
                  <el-divider content-position="center"><span style="font-size:16px">【外部产品】</span></el-divider>
                </el-col>
                <el-row v-for="(item, index) in model.productoutlist" :key="index">
                  <el-col :span="12">
                    <el-button type="text" @click="deleteOutProductRange(index)" size="medium" v-show="!(disableEditSubmit || disableSave)" style="float: left;padding-top: 6px"><i class="el-icon-remove-outline"></i>删除</el-button>
                    <el-form-item label="产品类别" label-width="100px" style="margin-left: 50px">
                      <el-input v-model="item.productname" disabled class="tl-ref-selector"> </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="金额" :prop="'productoutlist.' + index + '.fund'" :rules="rules.rulesForFundInfo"> <el-input-number v-model="item.fund" controls-position="right" :step="1" :min="0" :precision="2" class="unitInputNumber"></el-input-number><span class="unitSpan">万元</span> </el-form-item>
                  </el-col>
                </el-row>
              </el-row>
              <a id="background" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                项目描述
              </div>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="项目背景" prop="background" key="background">
                    <el-input v-model="model.background" type="textarea"  :rows="4" maxlength="1000" show-word-limit> </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="项目目标" prop="target" key="target">
                    <el-input v-model="model.target" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="总体策划" prop="summary" key="summary">
                    <el-input v-model="model.summary" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="竞争对手分析" prop="competitoranalysis" key="competitoranalysis" required="true">
                    <el-input v-model="model.competitoranalysis" type="textarea" placeholder="历史中标竞争对手以及本次潜在竞争对手" :rows="6"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <a id="risk" class="step-position">&nbsp;</a>
              <el-form>
                <tl-index-risk ref="riskForm" :projectinfo="model" :disableSave="disableEditSubmit || disableSave" @saveAndOpenRiskDialog="saveAndOpenRiskDialog"></tl-index-risk>
              </el-form>
              <!-- <a id="customer" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                客户信息
              </div>
              <el-row v-for="item in model.customerlist" :key="item.clientcode + item.clientname">
                <el-col :span="12">
                  <el-form-item label="客户名称">
                    <el-input v-model="item.clientname" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户部门">
                    <el-input v-model="item.clientdept" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="需求上报时间" prop="demandbegindate" :rules="model.purchasepattern && (model.purchasepattern === '3' || model.purchasepattern === '9') ? [] : rules.validateRequire">
                    <el-date-picker v-model="model.demandbegindate" type="date" placeholder="例：2022-01-01" value-format="yyyy-MM-dd"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="需求截止时间" prop="demandenddate" :rules="model.purchasepattern && (model.purchasepattern === '3' || model.purchasepattern === '9') ? [] : rules.validateRequire">
                    <el-date-picker v-model="model.demandenddate" type="date" placeholder="例：2022-01-01" value-format="yyyy-MM-dd"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="客户需求分析" prop="clientdemand" :rules="rules.rulesForCustomeryInfo">
                    <el-input v-model="model.clientdemand" type="textarea" :rows="6" maxlength="1000" show-word-limit> </el-input>
                  </el-form-item>
                </el-col>
              </el-row> -->
              <!-- <tl-project-customer-decision ref="projectCustomerDecision" :projectid="model.id"></tl-project-customer-decision> -->
              <!-- <a id="competitor" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                竞争对手
              </div>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="主要竞争对手" prop="competitor" :rules="rules.rulesForCompetitorInfo">
                    <el-input v-model="model.competitor" type="textarea" :rows="8" maxlength="1000" show-word-limit> </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="SWOT分析" prop="swot" :rules="rules.rulesForCompetitorInfo">
                    <el-input v-model="model.swot" type="textarea" :rows="8" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row> -->
              <a id="apply" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                申请信息
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人姓名" prop="username" :rules="rules.rulesForInfo">
                    <el-input v-model="model.username" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人工号" prop="usercode">
                    <el-input v-model="model.usercode" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人部门" prop="applydeptname">
                    <el-input v-model="model.applydeptname" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人公司" prop="applyorgname">
                    <el-input v-model="model.applyorgname" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <a id="history" class="step-position">&nbsp;</a>
              <el-collapse v-model="activeNames">
                <el-collapse-item name="1">
                  <template slot="title">
                    <div class="tl-form-line-title">
                      审批历史
                    </div>
                  </template>
                  <div>
                    <el-table v-show="listMode" class="tl-table" ref="mainTable" v-loading="loading" :data="datas" :max-height="200" @sort-change="doSortChange" row-key="id" border fit>
                      <el-table-column type="index" label="序号" width="55px" align="center"> </el-table-column>
                      <el-table-column prop="dispnodeid" label="流程节点" :show-overflow-tooltip="true" width="150px"> </el-table-column>
                      <el-table-column prop="dispapprovaluserid" label="审批人" width="150px" align="center"> </el-table-column>
                      <el-table-column prop="dispstate" label="状态" width="150px" align="center"> </el-table-column>
                      <el-table-column prop="approvaldate" label="审批时间" width="160px" sortable="custom" sort-by="approvaldate" align="center"></el-table-column>
                      <el-table-column prop="approvalopinion" label="审批意见" :show-overflow-tooltip="true" min-width="20"> </el-table-column>
                    </el-table>
                    <!-- 列表分页 -->
                    <el-row v-show="listMode" class="pagebar" ref="pager">
                      <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
                    </el-row>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-form>
            <div slot="footer" class="dialog-footer" style="float:right; margin-top: 10px">
              <el-button @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave" icon="el-icon-document-checked" type="primary">保存</el-button>
              <el-button @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval" type="primary"> <svg-icon icon-class="send" />提交审批 </el-button>
              <tl-attachment ref="attachmentRef" sourceType="MpmProject" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit">
                <el-button type="primary" :disabled="disableAttachment" icon="el-icon-paperclip" @click="$refs.attachmentRef.openUploadDialog()">{{ this.$refs.attachmentRef ? this.$refs.attachmentRef.btnTitle : '' }} [{{ this.$refs.attachmentRef ? (this.$refs.attachmentRef.fileList.length > 0 ? this.$refs.attachmentRef.fileList.length : this.$refs.attachmentRef.fileCount) : 0 }}] </el-button>
              </tl-attachment>
              <el-button @click="$refs.history.visible = true" :disabled="disableApprovalHistory" type="primary"> <svg-icon icon-class="list" />审批历史 </el-button>
              <el-button @click="doDelApproval" v-if="cancelApproval" :disabled="disableDelApproval" type="primary"> <svg-icon icon-class="undo" />取消审批 </el-button>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <tl-approval-history ref="history" sourceType="MpmProject" :sourceId="model.id" />
    <tlmpmProject-resource-pool-ref ref="mpmProjectResourcePoolRef" :title="'决策组选择'" @confirm="getMpmProjectResourceData" :fieldKey="'usercode'" :fieldValue="'username'" :externalSelectedRowKeys="extraParam === 'LINInvite' ? model.invitedecisionusercode : model.decisionusercode" :isSingleSelect="false" :externalQueryParam="externalDQueryParamForPool" :initDisplayData.sync="LINInviteParam"> </tlmpmProject-resource-pool-ref>
    <tlchange-ref ref="changeRef" @confirm="getChanceclueData" :usercode="model.projectmanagercode || user.code" :externalQueryParam="{ projectsource: model.projectsource }" :chanceclue2="model.chanceclue" :isSingleSelect="true" :fieldKey="rowKeyStr" :leadOrChanceLabel="leadOrChanceLabel"> </tlchange-ref>
    <tlChangeLevel-ref ref="changeLevelRef" @confirm="confirmChangeLevel"></tlChangeLevel-ref>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
import { mixin_page_fields_custom } from '@misui/mixins/mixin_page_fields_custom'
/** 子组件 */
import { validateNull } from '@tapui/utils/validate'
import tlmpmProjectResourcePoolRef from '@/views/mpm/mpmProjectResourcePool/refList'
import tlchangeRef from '@/views/mpm/mpmProject/refListChange'
import tlChangeLevelRef from './changeLevelCompent'
import meetListComp from '../../../components/meet/meetListComp'
// import tlProjectBidDate from '@/views/mpm/mpmProjectBidDate/edit'
import tlProjectCustomerDecision from '@/views/mpm/mpmProjectCustomerDecision/edit'
import tlIndexRisk from '@/views/mpm/mpmProjectRisk/indexComponent'
/** 工具类 */
import { formatDate } from '@tapui/utils/date'
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit, mixin_page_fields_custom],
  components: { tlmpmProjectResourcePoolRef, tlchangeRef, tlChangeLevelRef, tlProjectCustomerDecision, meetListComp, tlIndexRisk },
  data() {
    var validateForTab = (rule, value, callback) => {
      if (!value) {
        this.tabName = rule.tabname
        return callback(new Error('请输入内容'))
      } else {
        return callback()
      }
    }
    var validateForFund = (rule, value, callback) => {
      if (!value) {
        this.tabName = rule.tabname
        return callback(new Error('金额必填且不能为0！'))
      } else {
        return callback()
      }
    }
    return {
      moduleTitle: '项目立项',
      urlPrefix: '/mpm/projectpolymerization/',
      url: {
        // 额外的url
        queryOrgByDeptId: '/mpm/project/queryOrgByDeptId',
        list: '/cbo/approvalNodeIns/list',
        changeList: '/mpm/project/changeList',
        queryCeo: 'mpm/project/queryCeo',
        ifApprovalBack: 'mpm/project/ifApprovalBack',
        getProvinceCityList: '/mpm/projectpolymerization/getProvinceCityList',
        judgeDecisionUser: '/mpm/project/judgeDecisionUser'
      },
      tabName: 'projectbasicinfo',
      sorterInfo: {
        // 排序参数
        sidx: 'id',
        sord: 'desc'
      },
      midChangePoint: true,
      activeNames: [],
      datas: [],
      pageInfo: {
        // 分页参数
        currentPage: 1, // 当前页面
        pageSize: 10, // 每页记录数
        pageSizes: ['10', '50', '100'],
        totalCount: 0 // 总数
      },
      rowKeyStr: 'CODE',
      loading: false,
      visible: false,
      listMode: true,
      externalMQueryParamForPool: {},
      externalDQueryParamForPool: {},
      // 项目立项规则校验重写
      addRules: {
        // 基本信息TAB表单校验
        rulesForInfo: [{ validator: validateForTab, tabname: 'projectbasicinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }],
        // 案例概述TAB表单验证
        rulesForCustomeryInfo: [{ validator: validateForTab, tabname: 'projectcustomerinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }],
        rulesForCompetitorInfo: [{ validator: validateForTab, tabname: 'projectcompetitorinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }],
        rulesForFundInfo: [{ validator: validateForFund, tabname: 'projectproductinfo', trigger: 'blur' }, { required: 'true', message: '请输入内容', trigger: 'change' }]
      },
      // CEO信息
      tempdecisionusercode: '',
      tempdecisionusername: '',
      mainHeight: 1000,
      mainScrollElement: null,
      navList: [],
      constNavList: [{ name: '立项信息', on: true, code: 'basic' }, { name: '涉及产品范围', on: false, code: 'product' }, { name: '项目描述', on: false, code: 'background' }, { name: '项目风险', on: false, code: 'risk' }, { name: '申请信息', on: false, code: 'apply' }, { name: '审批历史', on: false, code: 'history' }],
      // 审批节点配置的额外参数
      extraParam: '',
      isApproval: false,
      // 判断是否是审批组件调用
      fromApproval: '',
      oldprojectlevel: '',
      // 项目等级，例：网级、省级等
      maxLevel: -1,
      cancelApproval: false,
      isAfterApproval: false,
      // 微前端调用该组件时传递的来源类型
      sourceType: '',
      // 是否已自动选择机会点标志位
      autoSelected: 0,
      // 微前端调用时传递的机会点编号
      chancecode: '',
      deptname: [],
      provinceCityList: [],
      gridData: [
        {
          projectlevel: 'A级',
          projectleveldetail: '1）战规中承接业务设计的项目。',
          sponsor: '系统部部长/其他相关方',
          owner: '经营管理部部长',
          manager: '省总'
        },
        {
          projectlevel: 'A级',
          projectleveldetail: '2）具有战略性、突破性，差距大、额度超大的项目。',
          sponsor: '系统部部长/其他相关方',
          owner: '经营管理部部长',
          manager: '省总'
        },
        {
          projectlevel: 'B级',
          projectleveldetail: '1）省招需要调动的公司资源较少，相对成熟的项目。',
          sponsor: '系统部部长/其他相关方',
          owner: '省总',
          manager: '副总/CTO'
        },
        {
          projectlevel: 'B级',
          projectleveldetail: '2）市、县级可参与金额300万元及以上。',
          sponsor: '系统部部长/其他相关方',
          owner: '省总',
          manager: '副总/CTO'
        },
        {
          projectlevel: 'C级',
          projectleveldetail: '基层项目。',
          sponsor: '省总',
          owner: '副总/CTO',
          manager: '行销/区域经理'
        }
      ],
      // 根据对应关系合并相同项目等级，3表示共三列等级相同
      spanArr: [2, 0, 2, 0, 1],
      dispLevelArr: ['A', 'B', 'C', 'D'],
      // 保存后是否打开项目风险新增页
      openRiskDialogFlag: false,
      // 内部产品金额之和
      productMoneyIn: 0,
      // 外部产品金额之和
      productMoneyOut: 0,
      ifRedMark: false,
      tipCount: 0
    }
  },
  props: {
    // 当前元素展示方式。默认为dialog，可选div/el-drawer
    render: {
      default: 'el-drawer',
      type: String
    }
  },
  watch: {
    isApproval(newVaule, oldVaule) {
      this.$set(this, 'isApproval', newVaule)
    },
    // 可参与金额和产品内金额之和保持一致
    'model.productlist': {
      handler(newVal, oldVal) {
        if (!validateNull(newVal) && newVal.length > 0 && Array.isArray(newVal)) {
          let productMoneyTotle = 0
          newVal.map((item) => {
            productMoneyTotle += item.fund
          })
          this.productMoneyIn = productMoneyTotle
          this.model.participatemoney = this.productMoneyIn + this.productMoneyOut
        }
      },
      deep: true
    },
    // 可参与金额和产品内金额之和保持一致
    'model.productoutlist': {
      handler(newVal, oldVal) {
        if (!validateNull(newVal) && newVal.length > 0 && Array.isArray(newVal)) {
          let productMoneyTotle = 0
          newVal.map((item) => {
            productMoneyTotle += item.fund
          })
          this.productMoneyOut = productMoneyTotle
          this.model.participatemoney = this.productMoneyIn + this.productMoneyOut
        }
      },
      deep: true
    },
    'model.projectlevel'(newLevel, oldLevel) {
      if (this.user.code !== '0070') {
        if ((newLevel === '0' || newLevel === '1') && (oldLevel === '2' || oldLevel === '3' || validateNull(oldLevel))) {
          let tempdecisionusercode = this.tempdecisionusercode
          let tempdecisionusername = this.tempdecisionusername
          let tempdecisionusercodeArr = tempdecisionusercode.split(',')
          let tempdecisionusernameArr = tempdecisionusername.split(',')
          if (this.model.decisionusercode) {
            let decisionusercodeArr = this.model.decisionusercode.split(',')
            let decisionusernameArr = this.model.decisionusername.split(',')
            // 从CD级切换到AB级时，如果原本CD级的决策组人员有林总、省总，需要取差集(去重)
            if (this.model.decisionusercode.indexOf(tempdecisionusercodeArr[1]) > 0 || this.model.decisionusercode.indexOf(tempdecisionusercodeArr[2]) > 0) {
              let decisionusercodeArrNew = decisionusercodeArr.filter((v) => !tempdecisionusercodeArr.find((item) => item === v))
              let decisionusernameArrNew = decisionusernameArr.filter((v) => !tempdecisionusernameArr.find((item) => item === v))
              let resultcodes = ''
              let resultnames = ''
              let code = []
              let name = []
              for (let i = 1; i < decisionusercodeArrNew.length - 1; i++) {
                code.push(decisionusercodeArrNew[i])
              }
              for (let i = 0; i < decisionusernameArrNew.length; i++) {
                name.push(decisionusernameArrNew[i])
              }
              let codes = code.join(',')
              resultcodes = codes ? ',' + codes + ',' : ''
              let names = name.join(',')
              resultnames = names ? ',' + names : ''
              tempdecisionusercode = tempdecisionusercode + resultcodes.substring(1)
              tempdecisionusername = tempdecisionusername + resultnames
              this.$set(this.model, 'decisionusercode', tempdecisionusercode)
              this.$set(this.model, 'decisionusername', tempdecisionusername)
            } else {
              tempdecisionusercode = tempdecisionusercode + this.model.decisionusercode.substring(1)
              tempdecisionusername = tempdecisionusername + ',' + this.model.decisionusername
              this.$set(this.model, 'decisionusercode', tempdecisionusercode)
              this.$set(this.model, 'decisionusername', tempdecisionusername)
            }
          } else if (!this.model.decisionusercode) {
            this.$set(this.model, 'decisionusercode', tempdecisionusercode)
            this.$set(this.model, 'decisionusername', tempdecisionusername)
          }
          // 判断切换后的人员是否在当前等级下可以被选中，如果在参照中无法被选中，将此人员过滤掉（即人员等级为CD级）
          this.judgeDecisionUser(newLevel)
        } else if ((newLevel === '2' || newLevel === '3') && (oldLevel === '0' || oldLevel === '1' || (validateNull(oldLevel) && (validateNull(this.model.state))))) {
          this.$set(this.model, 'projectattack', '')
          // 由AB切换到CD级
          let decisionusercodeArr = this.model.decisionusercode.split(',')
          let decisionusernameArr = this.model.decisionusername.split(',')
          let tempdecisionusercodeArr = this.tempdecisionusercode.split(',')
          let tempdecisionusernameArr = this.tempdecisionusername.split(',')
          if (this.model.decisionusercode.indexOf(tempdecisionusercodeArr[1]) > 0 || this.model.decisionusercode.indexOf(tempdecisionusercodeArr[2]) > 0) {
            // 取差集
            let decisionusercodeArrNew = decisionusercodeArr.filter((v) => !tempdecisionusercodeArr.find((item) => item === v))
            let decisionusernameArrNew = decisionusernameArr.filter((v) => !tempdecisionusernameArr.find((item) => item === v))
            let resultcodes = ''
            let resultnames = ''
            let code = []
            let name = []
            for (let i = 1; i < decisionusercodeArrNew.length - 1; i++) {
              code.push(decisionusercodeArrNew[i])
            }
            for (let i = 0; i < decisionusernameArrNew.length; i++) {
              name.push(decisionusernameArrNew[i])
            }
            let codes = code.join(',')
            resultcodes = codes ? ',' + codes + ',' : ''
            resultnames = name.join(',')
            this.$set(this.model, 'decisionusercode', resultcodes)
            this.$set(this.model, 'decisionusername', resultnames)
          }
          // 判断切换后的人员是否在当前等级下可以被选中，如果在参照中无法被选中，将此人员过滤掉（即人员等级为AB级）
          this.judgeDecisionUser(newLevel)
        }
      }
    }
  },
  computed: {
    projectattackList() {
      if (this.codeModel.hasOwnProperty('projectattackList')) {
        return this.codeModel.projectattackList.slice(0, 2)
      } else {
        return []
      }
    },
    // 是否标红
    ifRedBorder() {
      if (!this.model.bidbegindate || !this.model.bidenddate) {
        return false
      } else {
        let bidbegindate = new Date(this.model.bidbegindate).getTime()
        let bidenddate = new Date(this.model.bidenddate).getTime()
        // 日期相距不大于七天(12.1-12.8算七天)时，需提醒并将日期标红
        let t = bidenddate - bidbegindate
        let days = Math.ceil(t / (1000 * 3600 * 24))
        if (days <= 7 && this.isApproval) {
          // 标红时要求在审批中
          return true
        } else {
          return false
        }
      }
    },
    // 禁用取消审批
    disableDelApproval() {
      return this.stateAdd || this.stateEdit
    },
    // 禁用审批按钮
    disableApproval() {
      return (this.stateApproval && this.model.state !== 2) || this.uiOperateState === 4
    },
    // 禁用附件按钮
    disableAttachment() {
      return !this.model.id
    },
    leadOrChanceLabel() {
      if (this.model.projectsource && this.codeModel.projectSourceList) {
        return this.codeModel.projectSourceList.find((item) => item.code === this.model.projectsource).name
      } else {
        return '线索/机会点'
      }
    },
    historyLevel() {
      if (this.model.levelhistory) {
        return JSON.parse(this.model.levelhistory.replace(/\//g, '')).oldprojectlevel
      } else {
        return ''
      }
    },
    LINInviteParam() {
      if (this.extraParam === 'LINInvite') {
        return this.model.invitedecisionusername
      } else {
        return this.model.decisionusername
      }
    },
    // 挂网开标日期计算属性
    bidDateTime() {
      return this.model.purchasepattern === '11' || this.model.purchasepattern === '12' || this.model.purchasepattern === '13'
    },
    customerNeedbidDate() {
      if (!validateNull(this.model.customerlist)) {
        let customerlist = this.model.customerlist
        for (let i in customerlist) {
          if (customerlist[i].clientcatalog === 'A' || customerlist[i].clientcatalog === 'B' || customerlist[i].clientcatalog === 'C') {
            return true
          }
        }
        return false
      } else {
        return false
      }
    },
    projectlevelList() {
      if (this.codeModel.hasOwnProperty('projectlevelList')) {
        if (validateNull(this.model.state) || this.model.state === 0 || this.model.state === 2) {
          return this.codeModel.projectlevelList.filter((item) => item.code < 3)
        } else {
          return this.codeModel.projectlevelList
        }
      } else {
        return []
      }
    }
  },
  methods: {
    doSubmitEdit() {
      if (!this.beforeSubmit()) {
        return
      }
      if (this.isAdd) {
        this.doAdd()
      } else {
        this.doEdit()
      }
    },
    planStart(e) {
      if (this.model.planenddate) {
        var a = new Date(this.model.planstartdate).getTime()
        var b = new Date(this.model.planenddate).getTime()
        if (a > b) {
          this.$tap.alert('开始日期不得大于结束日期。', 'warning')
          this.$set(this.model, 'planstartdate', '')
          this.$set(this.model, 'bidcycle', '')
          return
        } else {
          var t = b - a
          var days = Math.ceil(t / (1000 * 3600 * 24)) + 1
          this.$set(this.model, 'bidcycle', days)
        }
      }
    },
    planEnd(e) {
      if (this.model.planstartdate === '' || typeof this.model.planstartdate === 'undefined') {
        this.$tap.alert('请先选择计划开始日期！', 'warning')
        this.$set(this.model, 'planenddate', '')
        this.$set(this.model, 'bidcycle', '')
        return
      }
      var c = new Date(this.model.planenddate).getTime()
      var d = new Date(this.model.planstartdate).getTime()
      var now = new Date().getTime()
      if (c < d) {
        this.$tap.alert('开始日期不得大于结束日期。', 'warning')
        this.$set(this.model, 'planenddate', '')
        this.$set(this.model, 'bidcycle', '')
        return
      }
      if (c < now) {
        this.$tap.alert('计划结束日期不得早于当前日期。', 'warning')
        this.$set(this.model, 'planenddate', '')
        this.$set(this.model, 'bidcycle', '')
        return
      }
      var a = c - d
      var days = Math.ceil(a / (1000 * 3600 * 24)) + 1
      this.$set(this.model, 'bidcycle', days)
      // 计划结束日期存储为选择日期的的23：59：59
      let date = new Date(c)
      let timeDate = ''
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      let h = 23 + ':'
      let m = 59 + ':'
      let s = 59
      timeDate = Y + M + D + h + m + s
      this.$set(this.model, 'planenddate', timeDate)
    },
    bidbegindate(e) {
      if (this.model.planstartdate === '' || typeof this.model.planstartdate === 'undefined' || this.model.planenddate === '' || typeof this.model.planenddate === 'undefined') {
        this.$tap.alert('请先选择计划开始日期和计划结束日期！', 'warning')
        this.$set(this.model, 'bidbegindate', '')
        return
      }
      var planenddate = new Date(this.model.planenddate).getTime()
      var planstartdate = new Date(this.model.planstartdate).getTime()
      var bidbegindate = new Date(this.model.bidbegindate).getTime()
      if (bidbegindate < planstartdate) {
        this.$tap.alert('挂网日期不能早于计划开始日期！', 'warning')
        this.$set(this.model, 'bidbegindate', '')
        return
      }
      if (bidbegindate > planenddate) {
        this.$tap.alert('挂网日期不能晚于计划结束日期！', 'warning')
        this.$set(this.model, 'bidbegindate', '')
        return
      }
      if (this.model.bidenddate) {
        var bidenddate = new Date(this.model.bidenddate).getTime()
        if (bidbegindate > bidenddate) {
          this.$tap.alert('挂网日期不能晚于开标日期！', 'warning')
          this.$set(this.model, 'bidbegindate', '')
          return
        }
        // 日期相距不大于七天(12.1-12.8算七天)时，需提醒并将日期标红
        let t = bidenddate - bidbegindate
        let days = Math.ceil(t / (1000 * 3600 * 24))
        if (days <= 7) {
          this.$tap.alert('开标日期与挂网日期间隔小于8天，请确认日期是否正确。', 'warning')
          // 标红
          this.ifRedMark = true
        } else {
          this.ifRedMark = false
        }
      }
    },
    bidenddate(e) {
      if (this.model.planstartdate === '' || typeof this.model.planstartdate === 'undefined' || this.model.planenddate === '' || typeof this.model.planenddate === 'undefined') {
        this.$tap.alert('请先选择计划开始日期和计划结束日期！', 'warning')
        this.$set(this.model, 'bidenddate', '')
        return
      }
      var planenddate = new Date(this.model.planenddate).getTime()
      var planstartdate = new Date(this.model.planstartdate).getTime()
      var bidenddate = new Date(this.model.bidenddate).getTime()
      if (bidenddate < planstartdate) {
        this.$tap.alert('开标日期不能早于计划开始日期！', 'warning')
        this.$set(this.model, 'bidenddate', '')
        return
      }
      if (bidenddate > planenddate) {
        this.$tap.alert('开标日期不能晚于计划结束日期！', 'warning')
        this.$set(this.model, 'bidenddate', '')
        return
      }
      if (this.model.bidbegindate) {
        var bidbegindate = new Date(this.model.bidbegindate).getTime()
        if (bidbegindate > bidenddate) {
          this.$tap.alert('挂网日期不能晚于开标日期！', 'warning')
          this.$set(this.model, 'bidenddate', '')
          return
        }
        // 日期相距不大于七天(12.1-12.8算七天)时，需提醒并将日期标红
        let t = bidenddate - bidbegindate
        let days = Math.ceil(t / (1000 * 3600 * 24))
        if (days <= 7) {
          this.$tap.alert('开标日期与挂网日期间隔小于8天，请确认日期是否正确。', 'warning')
          // 标红
          this.ifRedMark = true
        } else {
          this.ifRedMark = false
        }
      }
    },
    assignDefaultValue() {
      if (this.isAdd) {
        this.$set(this.model, 'applyorgcode', this.org.code)
        this.$set(this.model, 'applyorgname', this.org.name)
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'applydeptcode', this.dept.code)
        // this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'applydeptname', this.dept.fullname)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'docdate', new Date())
        this.$set(this.model, 'applydate', new Date())
        this.$set(this.model, 'projecttype', '0')
        this.$set(this.model, 'projectmanagercode', this.user.code)
        this.$set(this.model, 'projectmanager', this.user.name)
        this.$set(this.model, 'existbidscore', '1')
        this.$set(this.model, 'existbidscorestate', '0')
        this.$set(this.model, 'existbidscoresecond', '1')
      }
    },
    beforeApproval() {
      // 检验挂网开标日期和客户校验信息必填
      // if (!this.$refs.projectBidDate.validateBidDate()) {
      //   this.$tap.alert('请填写挂网日期和开标日期', 'warning')
      //   return false
      // }
      // if (!this.$refs.projectCustomerDecision.validateCustomerDecision()) {
      //   this.$tap.alert('请填写客户决策信息', 'warning')
      //   return false
      // }
      // CD级项目，如果用户没有选择项目Owner，默认由项目经理担任项目Owner
      if ((this.model.projectlevel === '2' || this.model.projectlevel === '3') && (this.model.ownercode === undefined || this.model.ownercode === null || this.model.ownercode === '')) {
        this.model.ownercode = this.model.projectmanagercode
        this.model.owner = this.model.projectmanager
      }
      return true
    },
    /** 提交审批 */
    doSubmitApproval() {
      if (!this.url.submit) {
        this.$tap.alert('请设置审批地址!', 'warning')
        return
      }
      if (validateNull(this.model.clientname) || validateNull(this.model.clientdept)) {
        this.$tap.alert('客户信息不能为空，请前往线索/机会点添加客户信息！', 'warning')
        return
      }
      let fileValidate = true
      this.$refs.form.validate((valid) => {
        if (!valid) {
          fileValidate = false
        }
      })
      if (!fileValidate) {
        return
      }
      if (!this.beforeSubmit()) {
        return
      }
      if (!this.beforeApproval()) {
        return
      }
      // 提交前校验产品不能为空
      if ((!this.model.productlist || this.model.productlist.length === 0) && (!this.model.productoutlist || this.model.productoutlist.length === 0)) {
        this.$tap.alert('涉及产品范围不能为空，请前往线索/机会点添加产品！', 'warning')
        return
      }
      this.saveLoading = true
      this.submitLoading = true
      this.$tap
        .confirm('确定提交审批吗？提交后，单据内容不可修改！')
        .then((_) => {
          this.$set(this.model, 'projectstate', '0')
          if (this.isAdd) {
            this.saveLoading = true
            // 增加唯一单号
            this.$set(this.model, 'billuid', this.uid)
            postAction(this.url.add, this.model)
              .then((res) => {
                if (res.success) {
                  this.$tap.message('添加成功', 'success')
                  this.queryData(res.result.id)
                  this.model = res.result
                  this.isAdd = false
                  putAction(this.url.submit, this.model).then((res) => {
                    if (res.success) {
                      this.$emit('refresh')
                      this.$tap.message(res.message, 'success')
                      this.queryData(this.model.id).then((_) => {
                        this.loaded()
                        this.submitLoading = false
                        this.saveLoading = false
                      })
                      this.afterApproval()
                    } else {
                      this.$tap.alert(res.message, 'warning')
                      this.submitLoading = false
                      this.saveLoading = false
                    }
                    this.afterSubmit()
                  })
                } else {
                  this.$tap.alert(res.message, 'warning')
                  this.saveLoading = false
                }
              })
              .catch((err) => {
                this.saveLoading = false
              })
          } else {
            this.saveLoading = true
            putAction(this.url.edit, this.model)
              .then((res) => {
                if (res.success) {
                  this.model = res.result
                  putAction(this.url.submit, this.model).then((res) => {
                    if (res.success) {
                      this.$emit('refresh')
                      this.$tap.message(res.message, 'success')
                      this.queryData(this.model.id).then((_) => {
                        this.loaded()
                        this.submitLoading = false
                        this.saveLoading = false
                      })
                      this.afterApproval()
                    } else {
                      this.$tap.alert(res.message, 'warning')
                      this.submitLoading = false
                      this.saveLoading = false
                    }
                    this.afterSubmit()
                  })
                } else {
                  this.$tap.alert(res.message, 'warning')
                  this.submitLoading = false
                }
              })
              .catch((err) => {
                this.saveLoading = false
              })
          }
        })
        .catch((_) => {
          this.saveLoading = false
          this.submitLoading = false
        })
    },
    /** 执行编辑提交 */
    doEdit() {
      this.saveLoading = true
      putAction(this.url.edit, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
            this.queryData(this.model.id).then((_) => {
              this.afterSubmit()
            })
            this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    // 选择项目所属部门
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const { id, code, fullname } = selectedDept
      this.$set(this.model, 'deptcode', code)
      this.$set(this.model, 'deptname', fullname)
      const param = {
        deptId: id
      }
      getAction(this.url.queryOrgByDeptId, param).then((res) => {
        if (res.success) {
          const { code: orgcode, name: orgname } = res.result
          this.$set(this.model, 'orgcode', orgcode)
          this.$set(this.model, 'orgname', orgname)
        } else {
          this.$tap.alert('已选部门关联公司信息错误，请联系系统管理员')
        }
      })
    },
    /** 抽屉组件必重写，主要为了执行resizeHandler方法、给mainScrollElement赋值，并添加监听事件，不要直接复制该方法 **/
    open() {
      this.model = {}
      this.activeNames = []
      this.cancelApproval = false
      this.resizeHandler()
      this.$nextTick(() => {
        this.getFieldsCustomSetting('projectpolymerization', 'el-form')
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          let params = {
            managercode: this.user.code
          }
          getAction(this.url.queryCeo, params).then((res) => {
            if (res.success) {
              let code = []
              let name = []
              res.result.forEach((element) => {
                code.push(element.usercode)
                name.push(element.username)
              })
              let codes = ',' + code.join(',') + ','
              let names = name.join(',')
              this.$set(this.model, 'decisionusercode', codes)
              this.$set(this.model, 'decisionusername', names)
              // 将CEO信息存到中间变量中
              this.tempdecisionusercode = codes
              this.tempdecisionusername = names
            }
          })
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
          // 获取省区地市信息
          this.getProvinceCityList()
        } else if (this.disableEditSubmit === false) {
          let params = {
            projectid: this.id
          }
          getAction(this.url.queryCeo, params).then((res) => {
            if (res.success) {
              let code = []
              let name = []
              res.result.forEach((element) => {
                code.push(element.usercode)
                name.push(element.username)
              })
              let codes = ',' + code.join(',') + ','
              let names = name.join(',')
              // 将CEO信息存到中间变量中
              this.tempdecisionusercode = codes
              this.tempdecisionusername = names
            }
          })
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            // 获取项目等级
            this.getMaxLevel()
            // 获取省区地市信息
            this.getProvinceCityList()
            this.loaded()
          })
        } else {
          let params = {
            projectid: this.id
          }
          getAction(this.url.queryCeo, params).then((res) => {
            if (res.success) {
              let code = []
              let name = []
              res.result.forEach((element) => {
                code.push(element.usercode)
                name.push(element.username)
              })
              let codes = ',' + code.join(',') + ','
              let names = name.join(',')
              // 将CEO信息存到中间变量中
              this.tempdecisionusercode = codes
              this.tempdecisionusername = names
            }
          })
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            // 获取项目等级
            this.getMaxLevel()
            // 获取省区地市信息
            this.getProvinceCityList()
            this.loaded()
          })
        }
        this.mainScrollElement = document.getElementById('mpmMainContainer').getElementsByClassName('el-scrollbar__wrap')[0]
        this.onMainScroll()
      })
      this.datas = []
      this.loadData({ currentPage: 1 })
    },
    getProvinceCityList() {
      let param = {
        usercode: this.isAdd ? this.user.code : this.model.projectmanagercode,
        deptcode: this.isAdd ? this.dept.code : this.model.deptcode
      }
      getAction(this.url.getProvinceCityList, param)
        .then((res) => {
          if (res.success) {
            this.provinceCityList = res.result.provinceCityList
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    /** 加载审批历史列表数据 */
    loadData(paramMap) {
      if (validateNull(paramMap) === false && Object.keys(paramMap).indexOf('currentPage') > -1) {
        this.pageInfo.currentPage = paramMap['currentPage']
      }
      // 查询条件
      this.sorterInfo.sidx = 'approvaldate'
      var params = this.getQueryParams()
      // 数据查询
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.datas = res.result.dataList
            this.pageInfo.totalCount = res.result.totalCount
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    /** 执行查询 */
    doQuery() {
      this.loadData({ currentPage: 1 })
    },
    /** 获取查询参数 */
    getQueryParams() {
      let param = {
        qry_sourcetype: 'MpmProject',
        qry_sourceid: 0
      }
      if (!this.isAdd) {
        if (this.isAfterApproval) {
          // 如果是提交审批之后加载审批历史，使用this.model.id加载数据
          param.qry_sourceid = this.model.id
          this.isAfterApproval = false
        } else {
          param.qry_sourceid = this.id
        }
      }
      Object.assign(param, this.sorterInfo)
      param.currentPage = this.pageInfo.currentPage
      param.pageSize = this.pageInfo.pageSize
      return param
    },
    /** 表格列排序 */
    doSortChange(columnInfo, prop, order) {
      if (columnInfo.column === null) {
        return
      }
      // 不排序
      if (validateNull(columnInfo.order)) {
        this.loadData({})
        return
      }
      // 升序或者降序排序
      if (columnInfo.column.sortBy) {
        this.sorterInfo.sidx = columnInfo.column.sortBy
      } else {
        this.sorterInfo.sidx = columnInfo.prop
      }
      this.sorterInfo.sord = columnInfo.order.replace('ending', '')
      this.loadData({})
    },
    /** 每页大小改变 */
    doChangeSize(val) {
      if (this.pageInfo.pageSize !== val) {
        this.pageInfo.pageSize = val
        this.pageInfo.currentPage = 1
        this.loadData({})
      }
    },
    /** 页面跳转 */
    doChangeIndex(val) {
      if (this.pageInfo.currentPage !== val) {
        this.pageInfo.currentPage = val
        this.loadData({})
      }
    },
    drawDiagram(map) {
      /* eslint-disable*/
      $('#history-myflow').html('')
      let restore = map.strdiagram
      restore = restore.replace(/'/g, '"')
      if (restore !== '') {
        restore = JSON.parse(restore)
      }
      let history = map.strhistory
      history = history.replace(/'/g, '"')
      history = history.replace(/activeRects/g, '"activeRects"')
      history = history.replace(/historyRects/g, '"historyRects"')
      history = history.replace(/rects/g, '"rects"')
      history = history.replace(/paths/g, '"paths"')
      history = history.replace(/code/g, '"code"')
      if (history !== '') {
        history = JSON.parse(history)
      }
      $('#history-myflow').myflow(
        $.extend(false, {
          basePath: '',
          restore: restore,
          editable: false,
          ...history
        })
      )
    },
    // 项目级别变更后，清空项目经理和决策组--2-7todo 暂时取消
    clear() {
      if (this.model.projectmanagercode || this.model.decisionusercode) {
        this.$set(this.model, 'projectmanagercode', '')
        this.$set(this.model, 'projectmanager', '')
        this.$set(this.model, 'decisionusercode', '')
        this.$set(this.model, 'decisionusername', '')
      }
    },
    /** 打开决策组成员参照 */
    openMpmProjectResourcePoolDialog() {
      const { projectlevel, projecttype } = this.model
      if (!projectlevel) {
        this.$tap.alert('请先选择项目级别！', 'warning')
        this.$refs.mpmProjectResourcePoolRef.visible = false
      } else {
        this.externalDQueryParamForPool = {
          projectlevel: projectlevel,
          projecttype: projecttype
        }
        this.$refs.mpmProjectResourcePoolRef.visible = true
      }
    },
    /** 获取决策组成员参照数据 */
    getMpmProjectResourceData(selectionRow, selectKey, selectionValue) {
      // 如果是林总邀请审批
      if (this.extraParam === 'LINInvite') {
        let resultcodes = ''
        let resultnames = ''
        if (Array.isArray(selectionRow)) {
          if (selectionRow.length > 0) {
            let code = []
            let name = []
            selectionRow.forEach((element) => {
              code.push(element.usercode)
              name.push(element.username)
            })
            if (code.length > 0 && name.length > 0) {
              resultcodes += ',' + code.join(',') + ','
              resultnames += name.join(',')
            }
          }
        } else {
          if (selectionRow.usercode) {
            resultcodes += ',' + selectionRow.usercode + ','
            resultnames += selectionRow.username
          }
        }
        this.$set(this.model, 'invitedecisionusercode', resultcodes)
        this.$set(this.model, 'invitedecisionusername', resultnames)
      } else {
        // 如果是AB项目
        if (this.model.projectlevel === '0' || this.model.projectlevel === '1') {
          // 将CEO数据分割为数组
          let tempdecisionusercodeArr = this.tempdecisionusercode.split(',')
          let resultcodes = this.tempdecisionusercode
          let resultnames = this.tempdecisionusername
          if (Array.isArray(selectionRow)) {
            if (selectionRow.length > 0) {
              let code = []
              let name = []
              selectionRow.forEach((element) => {
                // 移除选择的人员中的CEO数据
                if (tempdecisionusercodeArr.indexOf(element.usercode) < 0) {
                  code.push(element.usercode)
                  name.push(element.username)
                }
              })
              if (code.length > 0 && name.length > 0) {
                resultcodes += code.join(',') + ','
                resultnames += ',' + name.join(',')
              }
            }
          } else {
            if (selectionRow.usercode && tempdecisionusercodeArr.indexOf(selectionRow.usercode) < 0) {
              resultcodes += selectionRow.usercode + ','
              resultnames += ',' + selectionRow.username
            }
          }
          this.$set(this.model, 'decisionusercode', resultcodes)
          this.$set(this.model, 'decisionusername', resultnames)
        } else {
          // 如果是CD级项目
          let resultcodes = ''
          let resultnames = ''
          if (Array.isArray(selectionRow)) {
            if (selectionRow.length > 0) {
              let code = []
              let name = []
              selectionRow.forEach((element) => {
                code.push(element.usercode)
                name.push(element.username)
              })
              let codes = code.join(',')
              resultcodes = codes ? ',' + codes + ',' : ''
              resultnames = name.join(',')
            }
          } else {
            resultcodes = ',' + selectionRow.usercode + ','
            resultnames = selectionRow.username
          }
          this.$set(this.model, 'decisionusercode', resultcodes)
          this.$set(this.model, 'decisionusername', resultnames)
        }
      }
    },
    /** 打开机会点参照 */
    openChanceclueDialog() {
      if (!this.model.projectsource) {
        this.$tap.alert('请先选择项目来源！', 'warning')
      } else {
        this.$refs.changeRef.visible = true
      }
    },
    /** 获取机会点参照数据 */
    getChanceclueData(selectionRow, selectKey, selectionValue) {
      var participatemoney = 0
      //项目名称，可参与金额须手填
      this.midChangePoint = selectionRow.length <= 1
      var chanceclue = ''
      var clientlevel = ''
      // 先清空项目经理
      this.$set(this.model, 'projectmanager', '')
      this.$set(this.model, 'projectmanagercode', '')
      // 清空客户数组
      this.$set(this.model, 'customerlist', [])
      // 公司和非公司产品
      var proType = []
      var proOutType = []
      let competitorList = []
      let bidbegintimeList = []
      let bidendtimeList = []
      //循环取值
      selectionRow.forEach((item, index) => {
        this.$set(this.model, 'projectname', item.PROJECT_NAME)
        this.$set(this.model, 'projectmanager', item.GARDENER_NAME)
        this.$set(this.model, 'projectmanagercode', item.GARDENER_CODE)
        this.$set(this.model, 'deptname', item.DEPT_COMMON_CODE_1NAME)
        this.$set(this.model, 'deptcommoncode', item.DEPT_COMMON_CODE_1)
        //从机会点获取到的creator_dept_code 作为创建部门编码(deptcode)，根据创建部门编码，走审批
        this.$set(this.model, 'deptcode', item.CREATOR_DEPT_CODE)
        this.$set(this.model, 'participatemoney', item.OUR_PROCDUCT_FUND)
        this.$set(this.model, 'clientname', item.CLIENT_NAME)
        this.$set(this.model, 'clientdept', item.CLIENT_DEPT_NAME)
        if (item.BID_TYPE) {
           this.$set(this.model, 'purchasepattern', item.BID_TYPE)
        }
        participatemoney = participatemoney + parseFloat(item.OUR_PROCDUCT_FUND)
        this.$set(this.model, 'participatemoney', participatemoney)
        // 构造竞争对手信息
        if (item.COMPETITOR_INFO) {
          let competitorItem = {}
          competitorItem.name = item.PROJECT_NAME
          competitorItem.info = item.COMPETITOR_INFO
          competitorList.push(competitorItem)
        }
        // 如果是招标类的机会点，
        if(item.BID_TYPE === '11' || item.BID_TYPE === '12' || item.BID_TYPE === '13') {
          item.FORECAST_TIME ? bidbegintimeList.push(item.FORECAST_TIME) : null
          item.BID_END_DATE  ? bidendtimeList.push(item.BID_END_DATE) : null
        }

        //填充机会点,拼接客户类型（网、省、市、县级）
        if (chanceclue.length > 0) {
          chanceclue = chanceclue + ',' + item.CODE
          clientlevel = clientlevel + ',' + item.CLIENT_LEVEL
        } else {
          chanceclue = item.CODE
          clientlevel = item.CLIENT_LEVEL
        }
        //填充涉及产品范围，获取产品类型，拼装产品金额，请求报文为json数组
        if (item.CATALOG) {
          var tempCatalog = item.CATALOG.split(',')
          var tempCatalogCode = item.CATALOGCODE.split(',')
          var tempFund = item.FUND.split(',')
          var tempProductLine = item.LINE.split(',')
          tempCatalog.forEach((element, index) => {
            let flag = false
            for (var i in proType) {
              if (proType[i].productname === element) {
                flag = true
                var tempProduct = { productlinecode: proType[i].productlinecode, productname: proType[i].productname, productcode: proType[i].productcode, fund: parseFloat(proType[i].fund) + parseFloat(tempFund[index]) }
                proType.splice(i, 1, tempProduct)
                break
              }
            }
            if (!flag) {
              proType.push({ productlinecode: tempProductLine[index], productname: element, productcode: tempCatalogCode[index], fund: parseFloat(tempFund[index]) })
            }
          })
        }
        //填充外部产品范围，获取产品类型，拼装产品金额，请求报文为json数组
        if (item.CATALOGOUT) {
          var tempCatalogOut = item.CATALOGOUT.split(',')
          var tempFundOut = item.FUNDOUT.split(',')
          tempCatalogOut.forEach((element, index) => {
            let flagOut = false
            for (var i in proOutType) {
              if (proOutType[i].productname === element) {
                flagOut = true
                var tempProductOut = { productname: proOutType[i].productname, fund: parseFloat(proOutType[i].fund) + parseFloat(tempFundOut[index]) }
                proOutType.splice(i, 1, tempProductOut)
                break
              }
            }
            if (!flagOut) {
              proOutType.push({ productname: element, fund: parseFloat(tempFundOut[index]) })
            }
          })
        }
        // 向客户信息数组中赋值
        this.$nextTick(() => {
          if (!this.model.customerlist.find((cus) => cus.clientname === item.CLIENT_NAME)) {
            this.model.customerlist.push({
              clientname: item.CLIENT_NAME,
              clientdept: item.CLIENT_DEPT_NAME,
              clientcode: item.CLIENT_CODE,
              clientcatalog: item.CLIENT_CATALOG,
              customersourcetype: item.CUSTOMER_SOURCE_TYPE,
              sourcetype: 'MpmProject'
            })
          }
        })
      })
      // 找到最早的开标和挂网日期，赋值
      let minBegin = ''
      let minEnd = ''
      if(bidbegintimeList.length > 0) {
        minBegin = bidbegintimeList[0]
        for(let item of bidbegintimeList) {
          let minDate = new Date(minBegin)
           let itemDate = new Date(item)
          if(itemDate < minDate) {
            minBegin = item
          }
        }
      }
      if(bidendtimeList.length > 0) {
        minEnd = bidendtimeList[0]
        for(let item of bidendtimeList) {
          let minDate = new Date(minEnd)
           let itemDate = new Date(item)
          if(itemDate < minDate) {
            minBegin = item
          }
        }
      }
      this.$set(this.model, 'bidbegindate', minBegin)
      this.$set(this.model, 'bidenddate', minEnd)
      // 构造竞争对手分析字段
      let competitorAnalysis = ''
      let reg = /【[0-9]*】/g
      if (competitorList.length > 1){
        // 有多个来源填写
        let itemString = ''
        for(let item of competitorList) {
          itemString = item.name + ':\n'
          let info = item.info
          info = info.replaceAll('对手名称：','')
          info = info.replaceAll(', 策略分析','')
          info = info.replaceAll(reg,this.replaceNumber2)
          itemString += info
          competitorAnalysis += itemString.substr(0,itemString.length-2) + '。\n'
          itemString = ''
        }
      } else if (competitorList.length === 1) {
        // 单个来源，直接格式匹配替换
        competitorAnalysis = competitorList[0].info
        competitorAnalysis = competitorAnalysis.replaceAll('对手名称：','')
        competitorAnalysis = competitorAnalysis.replaceAll(', 策略分析','')
        competitorAnalysis = competitorAnalysis.replaceAll(reg,this.replaceNumber)
        competitorAnalysis = competitorAnalysis.substr(0,competitorAnalysis.length-1) + '。\n'
      }
      let tempClientCode = ''
      let tempClientName = ''
      let tempClientSourcetype = ''
      let tempClientDept = ''
      this.$set(this.model, 'competitoranalysis', competitorAnalysis)
      this.$set(this.model, 'productlist', proType)
      this.$set(this.model, 'productoutlist', proOutType)
      this.$set(this.model, 'chanceclue', chanceclue)
      this.$set(this.model, 'clientlevel', clientlevel)
      this.$nextTick(() => {
        this.model.customerlist.forEach((item, index) => {
          if (index === 0) {
            if (item.clientname !== null && item.clientname !== '') {
              tempClientName = item.clientname
            }
            tempClientCode = item.clientcode
            tempClientSourcetype = item.customersourcetype
            if (item.clientdept !== null && item.clientdept !== '') {
              tempClientDept = item.clientdept
            }
          } else {
            if (item.clientname !== null && item.clientname !== '') {
              tempClientName = tempClientName + ',' + item.clientname
            }
            if (item.clientdept !== null && item.clientdept !== '') {
              tempClientDept = tempClientDept + ',' + item.clientdept
            }
            tempClientCode = tempClientCode + ',' + item.clientcode
            tempClientSourcetype = tempClientSourcetype + ',' + item.customersourcetype
          }
        })
        this.$set(this.model, 'clientcode', tempClientCode)
        this.$set(this.model, 'clientname', tempClientName)
        this.$set(this.model, 'clientsourcetype', tempClientSourcetype)
        this.$set(this.model, 'clientdept', tempClientDept)
        this.$refs.form.clearValidate()
      })
    },
    // 正则替换函数
    replaceNumber(content,index,str) {
      return content.substr(1,content.length-2) + '、'
    },
    replaceNumber2(content,index,str) {
      return '    ' + content.substr(1,content.length-2) + '、'
    },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      this.$set(this.model, 'billuid', this.uid)
      postAction(this.url.add, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.queryData(res.result.id).then((_) => {
              this.afterSubmit()
            })
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    //数据库字符串对象去特殊字符
    loaded() {
      // 挂网开标日期组件
      // this.$refs.projectBidDate.isAdd = this.isAdd
      // this.$refs.projectBidDate.disableEditSubmit = this.disableEditSubmit
      // this.$refs.projectBidDate.disableSave = this.disableSave
      // this.$refs.projectBidDate.open()
      // this.$set(this.model, 'projectBidDate', this.$refs.projectBidDate.model.projectDateList)
      // 客户决策信息组件
      // this.$refs.projectCustomerDecision.isAdd = this.isAdd
      // this.$refs.projectCustomerDecision.disableEditSubmit = this.disableEditSubmit
      // this.$refs.projectCustomerDecision.disableSave = this.disableSave
      // this.$refs.projectCustomerDecision.open()
      // this.$set(this.model, 'projectCustomerDecision', this.$refs.projectCustomerDecision.model.projectCustomerList)
      // 审批中项目立项，记录项目原级别
      if (this.model.state === 1) {
        this.oldprojectlevel = this.model.projectlevel
      }
      // 给midChangePoint赋初始值
      if (this.model.chanceclue) {
        this.midChangePoint = this.model.chanceclue.split(',') <= 1
      }
      if (this.stateApproval) {
        // 判断打开的项目在决策组审批节点是否有被退回
        let queryparam = { projectcode: this.model.projectcode }
        getAction(this.url.ifApprovalBack, queryparam).then((res) => {
          if (res.success) {
            // 若有被退回则开放取消审批权限
            if (res.result) {
              this.cancelApproval = true
            }
          }
        })
      }
      // 通知父组件刷新
      if (this.autoSelected !== 0 || !this.isAdd) {
        this.$emit('refresh')
      }
      // 自动选择机会点
      this.autoSelect()
      // 若为不可编辑状态则清空placeholder
      if (this.disableEditSubmit || this.disableSave) {
        this.$refs.form.fields.forEach((item) => {
          if (item.$children[1].$options._componentTag === 'el-input') {
            item.$children[1].getInput().placeholder = ''
          }
        })
      }
      this.deptname = []
      if (this.model.deptname1) {
        this.deptname.push(this.model.deptname1)
      }
      if (this.model.deptname2) {
        this.deptname.push(this.model.deptname2)
      }
      if (this.model.deptname3) {
        this.deptname.push(this.model.deptname3)
      }
      // navList赋值
      this.setNavListValue()
      this.$refs.form.clearValidate()
    },
    setNavListValue() {
      this.navList = []
      this.constNavList.forEach((item) => this.navList.push(item))
      if (this.extraParam !== 'CEO' && this.model.approvaltype === '1') {
        this.navList.splice(1, 0, { name: '会议决策记录', on: false, code: 'meetresolution' })
      }
    },
    close() {
      this.maxLevel = -1
    },
    /** 打开调整项目级别的弹框 **/
    openChangeLevelDialog() {
      this.$set(this.model, 'oldprojectlevel', this.oldprojectlevel)
      this.$refs.changeLevelRef.projectlevelList = this.codeModel.projectlevelList
      this.$refs.changeLevelRef.dispprojectdefaultlevel = this.codeModel.projectlevelList.find((item) => item.code === this.model.oldprojectlevel).name
      this.$set(this.$refs.changeLevelRef.model, 'projectlevel', this.model.projectlevel)
      this.$set(this.$refs.changeLevelRef.model, 'dispprojectlevel', this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel).name)
      this.$set(this.$refs.changeLevelRef.model, 'changelevelreason', this.model.changelevelreason)
      this.$refs.changeLevelRef.visible = true
    },
    /** 填写调整项目等级原因后回写数据 **/
    confirmChangeLevel(data) {
      this.$set(this.model, 'projectlevel', data.projectlevel)
      this.$set(this.model, 'changelevelreason', data.changelevelreason)
    },
    afterSubmit() {
      this.loaded()
      if (this.openRiskDialogFlag) {
        // 如果通过风险新增保存立项，需要打开风险新增页面
        this.$refs.riskForm.openAddDialog('editForm')
        this.openRiskDialogFlag = false
      }
    },
    /** 抽屉组件必有 **/
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100 - (this.isApproval ? 110 : 0)
    },
    /** 抽屉组件必有 **/
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    /** 抽屉组件必有 **/
    formatDate(date) {
      return formatDate(new Date(date ? date.toString().replace(/\-/g, '/') : date), 'yyyy-MM-dd')
    },
    /** 点击左侧导航，抽屉组件必有 **/
    clickNav(code) {
      this.navList.forEach((m) => {
        if (m.code === code) {
          m.on = true
        } else {
          m.on = false
        }
      })
      let element = document.getElementById(code)
      if (element === null) return
      let goY = element.getBoundingClientRect().y - 75
      this.mainScrollElement.scrollTop += goY
    },
    /** 页面滚动时，动态改变左侧导航选中的元素，抽屉组件必有 **/
    onMainScroll() {
      this.mainScrollElement.addEventListener('scroll', () => {
        let currentTop = this.mainScrollElement.scrollTop
        let code = ''
        for (let element of document.getElementsByClassName('step-position')) {
          if (element.getBoundingClientRect().y >= 0) {
            code = element.id
            break
          }
        }
        this.navList.forEach((m) => {
          if (m.code === code) {
            m.on = true
          } else {
            m.on = false
          }
        })
      })
    },
    /** 修改项目来源时将机会点/线索编号、项目名称、项目金额、默认等级、级别调整原因和其他中间变量清空 **/
    changeSource(select) {
      this.$set(this.model, 'chanceclue', '')
      this.$set(this.model, 'projectname', '')
      this.$set(this.model, 'participatemoney', '')
      this.$set(this.model, 'projectdefaultlevel', '')
      this.$set(this.model, 'changelevelreason', '')
      this.$set(this.model, 'productlist', [])
      this.$set(this.model, 'productoutlist', [])
      this.$set(this.model, 'clientname', '')
      this.$set(this.model, 'clientdept', '')
    },
    openMeetDialog(val, editForm) {
      this.navList = []
      this.constNavList.forEach((item) => this.navList.push(item))
      if (val === '1') {
        this.navList.splice(0, 0, { name: '会议决策记录', on: false, code: 'ceomeetresolution' })
      } else {
        this.navList.splice(this.navList.findIndex((item) => item.code === 'ceomeetresolution'), 1)
      }
      // 保存审批类型
      const { id, approvaltype, deptcode } = this.model
      const param = { id, approvaltype, deptcode }
      putAction(this.url.edit, param).then((res) => {
        if (!res.success) {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    /** PMO标准化审批前调用 **/
    saveInfo(resolve, reject) {
      this.$refs.PMONodeForm.validate((valid) => {
        if (!valid) {
          this.$tap.alert('请选择项目类型！', 'warning')
          reject()
        }
      })
      // C级项目春季/秋季攻势不赋值
      if (this.model.projectlevel === '2') {
        this.$set(this.model, 'projectattack', '')
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          putAction(this.url.edit, this.model)
            .then((res) => {
              if (res.success) {
                this.$emit('refresh')
                resolve()
              } else {
                this.$tap.alert(res.message, 'warning')
                reject()
              }
            })
            .catch((err) => {
              this.$tap.alert('修改项目信息失败，请联系系统管理员', 'warning')
              reject()
            })
        } else {
          reject()
        }
      })
    },
    /** CEO审批用方法 **/
    saveApprovalTypeInfo(resolve, reject) {
      const { id, approvaltype, deptcode } = this.model
      if (!approvaltype) {
        this.$tap.alert('请选择审批类型')
        reject()
      } else {
        const param = { id, approvaltype, deptcode }
        putAction(this.url.edit, param)
          .then((res) => {
            if (res.success) {
              if (approvaltype == '0' || (approvaltype == '1' && this.$refs.meetlist.datas.length > 0)) {
                resolve()
              } else {
                if(this.tipCount === 0) {
                  this.$tap.alert('请先创建会议，与各决策组成员达成一致后审批！', 'warning')
                  this.tipCount = this.tipCount + 1
                  reject()
                }else{
                  resolve()
                }
              }
            } else {
              this.$tap.alert(res.message, 'warning')
            }
          })
          .catch((err) => {
            this.$tap.alert('保存审批类型信息失败，请联系系统管理员', 'warning')
          })
      }
    },
    /** 林总邀请审批 **/
    saveInviteInfo(resolve, reject) {
      // 林总邀请审批这个节点，既要选择项目级别，也要选择决策组人员
      // 校验邀请决策的人员是否重复
      const { decisionusercode, invitedecisionusercode, projectlevel } = this.model
      // 项目级别必须选择，决策组人员不是必须选的
      if (projectlevel === '' || projectlevel === undefined) {
        this.$tap.alert('请选择项目级别！', 'warning')
        reject()
      } else {
        let flag = false
        if (decisionusercode && invitedecisionusercode) {
          let decisionusercodeArray = decisionusercode.split(',')
          let invitedecisionusercodeArray = invitedecisionusercode.split(',')
          flag = decisionusercodeArray.find((item) => (item ? invitedecisionusercodeArray.indexOf(item) >= 0 : false))
          if (flag) {
            this.$tap.alert('邀请决策的人员和原决策组人员重复，请重新选择！', 'warning')
            reject()
          } else {
            // 把邀请决策的人员添加进原决策组人员
            this.model.decisionusercode = this.model.decisionusercode + this.model.invitedecisionusercode.substring(1)
            this.model.decisionusername = this.model.decisionusername + ',' + this.model.invitedecisionusername
          }
        }
        if (!flag) {
          // 向后台传输原项目等级，用于拼接出levelHistory
          this.$set(this.model, 'oldprojectlevel', this.oldprojectlevel)
          putAction(this.url.edit, this.model)
            .then((res) => {
              if (res.success) {
                this.$emit('refresh')
                resolve()
              } else {
                this.$tap.alert(res.message, 'warning')
                reject()
              }
            })
            .catch((err) => {
              this.$tap.alert('添加邀请决策失败，请联系系统管理员', 'warning')
              reject()
            })
        }
      }
    },
    /** 林总审批 **/
    saveProjectLevelInfo(resolve, reject) {
      // 向后台传输原项目等级，用于拼接出levelHistory
      this.$set(this.model, 'oldprojectlevel', this.oldprojectlevel)
      putAction(this.url.edit, this.model)
        .then((res) => {
          if (res.success) {
            this.$emit('refresh')
            resolve()
          } else {
            this.$tap.alert(res.message, 'warning')
            reject()
          }
        })
        .catch((err) => {
          this.$tap.alert('修改项目信息失败，请联系系统管理员', 'warning')
          reject()
        })
    },
    /** 获取项目等级，例网级、省级 **/
    getMaxLevel() {
      let param = {
        currentPage: 1,
        pageSize: 500,
        projectsource: this.model.projectsource,
        sidx: 'sortcode',
        sord: 'asc',
        usercode: this.model.projectmanagercode
      }
      if (this.model.chanceclue) {
        getAction(this.url.changeList, param).then((res) => {
          if (res.success) {
            // 当前用户已选择的线索/机会点
            let codes = this.model.chanceclue.split(',')
            // 当前用户所有的线索/机会点
            res.result.dataList.forEach((item) => {
              if (codes.find((code) => code === item.CODE)) {
                // 取客户等级最大的作为项目等级
                this.maxLevel = Math.max(this.maxLevel, Number(item.CLIENT_LEVEL))
              }
            })
          } else {
            this.$tap.alert('获取线索/机会点列表错误，请联系管理员')
          }
        })
      }
    },
    // 提交审批之后刷新审批历史页面
    afterApproval() {
      this.isAfterApproval = true
      this.loadData({ currentPage: 1 })
    },
    // 保存之前获取挂网开标日期子表信息
    beforeSubmit() {
      if (validateNull(this.model.chanceclue)) {
        this.$tap.alert('请选择线索/机会点！', 'warning')
        return false
      }
      if (validateNull(this.model.projectlevel)) {
        this.$tap.alert('请选择项目等级！', 'warning')
        return false
      }
      // 拼接评标细则打标字段，1为历史数据或挂网开标日期为空数据，否则为0
      if (validateNull(this.model.bidbegindate) || validateNull(this.model.bidenddate)) {
        this.$set(this.model, 'bidscoreflag', 1)
      } else {
        this.$set(this.model, 'bidscoreflag', 0)
      }
      // C级项目春季/秋季攻势不赋值
      if (this.model.projectlevel === '2') {
        this.$set(this.model, 'projectattack', '')
      }
      return true
    },
    // 删除公司产品
    deleteProductRange(index) {
      if (this.model.productlist.length === 1) {
        this.$tap.alert('内部产品数量为1时，不允许删除')
      } else {
        this.model.productlist.splice(index, 1)
      }
    },
    // 删除非公司产品
    deleteOutProductRange(index) {
      if (this.model.productoutlist.length === 1) {
        this.$tap.alert('外部产品数量为1时，不允许删除')
      } else {
        this.model.productoutlist.splice(index, 1)
      }
    },
    autoSelect() {
      this.$nextTick(() => {
        if (this.autoSelected === 0 && this.isAdd) {
          if (this.sourceType === 'chance') {
            // 模拟手动选择机会点
            this.$set(this.model, 'projectsource', '2')
            this.changeSource()
            setTimeout(() => {
              let param = {
                qry_chancecode: this.chancecode,
                projectsource: this.model.projectsource,
                usercode: this.user.code,
                currentPage: 1,
                pageSize: 10
              }
              getAction('/mpm/project/changeList', param).then((res) => {
                if (res.success) {
                  this.getChanceclueData(res.result.dataList)
                } else {
                  this.$tap.alert('获取线索/机会点列表错误，请联系管理员')
                }
              })
            }, 1000)
          }
        }
        this.autoSelected = 1
      })
    },
    changeDeptname() {
      this.model.deptname1 = this.deptname[0]
      this.model.deptname2 = this.deptname[1] || null
      this.model.deptname3 = this.deptname[2] || null
    },
    judgeDecisionUser(newLevel) {
      if (!validateNull(this.model.decisionusercode)) {
        getAction(this.url.judgeDecisionUser, { decisionusercode: this.model.decisionusercode, decisionusername: this.model.decisionusername, newlevel: newLevel }).then((res) => {
          if (res.success) {
            this.$set(this.model, 'decisionusercode', res.result.newdecisionusercode)
            this.$set(this.model, 'decisionusername', res.result.newdecisionusername)
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    /** 查询编码 */
    doQueryCode() {
      if (this.url.queryCodeList) {
        getAction(this.url.queryCodeList, {}).then((res) => {
          if (res.success) {
            res.result.MpmPurchasePatternList = res.result.MpmPurchasePatternList.filter((item) => Number(item.code) > 10)
            this.codeModel = res.result
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      }
    },
    // 保存立项并打开风险新增页面
    saveAndOpenRiskDialog() {
      this.openRiskDialogFlag = true
      this.doSubmitEdit()
    }
  },
  created() {
    // 抽屉组件必有
    window.addEventListener('resize', this.resizeHandler)
  },
  destroyed() {
    // 抽屉组件必有
    window.removeEventListener('resize', this.resizeHandler)
  }
}
</script>
<style scoped lang="scss">
.red-border /deep/ .el-input__inner {
  color: red !important;
  border-color: red !important;
}
.mpm-project-header .toolbar {
  display: flex;
  justify-content: flex-end;
  position: absolute;
  z-index: 10;
  right: 15px;
  top: 15px;
  .el-button.is-plain {
    flex-shrink: 0;
    padding: 9px 15px;
    border-radius: 6px;
    font-size: 14px;
  }
}
.formLine {
  position: relative;
  margin: 0 auto;
  width: 900px;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);
}
.formLineTitle {
  position: absolute;
  left: 12%;
  font-family: 'kaiTi';
  background-color: #ffffff;
  padding: 0 15px;
  transform: translateX(-50%) translateY(-50%);
}
</style>
